<!-- 银行记账 -->
<template>
  <div class="bank-account">
    <div ref="dgtools" class="filter-container">
      <div class="dgts-row">
        <div class="dgts-text">
          <b class="tr-it">收入:{{ totalGath }}元</b>
          <el-divider direction="vertical"></el-divider>
          <b class="tr-it">支出:{{ totalPay }}元</b>
          <el-divider direction="vertical"></el-divider>
          <b class="tr-it">余额:{{ getBalance }}</b>
        </div>

        <el-select v-model="dg.ps.bankArr" placeholder="银行名称" clearable multiple collapse-tags
          style="width: 250px; margin: 0 20px 0 10px">
          <el-option v-for="(it, i) in bankOptions" :key="i" :label="it.bankName" :value="it.bankName + '/' + it.cardNo">
          </el-option>
        </el-select>

        <el-button type="primary" icon="el-icon-upload2" @click="handleImport">
          银行账导入
        </el-button>

        <el-button type="primary" icon="el-icon-download" @click="handleDown">
          模板下载
        </el-button>
      </div>

      <div class="dgts-fm">
        <el-input clearable style="width: 130px" placeholder="对方户名" v-model="dg.ps.transName">
        </el-input>

        <el-input clearable style="width: 130px" placeholder="客户名称" v-model="dg.ps.cusName">
        </el-input>

        <el-select v-model="dg.ps.timeType" placeholder="时间查询类型" style="width: 100px">
          <el-option label="添加时间" value="0"></el-option>
          <el-option label="交易时间" value="1"></el-option>
        </el-select>

        <el-date-picker v-model="dg.ps.setime" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="yyyy-MM-dd" clearable style="width: 210px" />

        <el-input style="width: 100px" placeholder="交易金额" v-model="dg.ps.findMoney">
        </el-input>

        <el-select clearable v-model="dg.ps.isCheck" placeholder="报销状态" style="width: 100px">
          <el-option label="已结算" value="-1"></el-option>
          <el-option label="未操作" value="0"></el-option>
          <el-option label="已报销" value="1"></el-option>
        </el-select>

        <el-select clearable v-model="dg.ps.moneyType" placeholder="请选择金额类型" style="width: 180px">
          <el-option v-for="item in moneyOptions" :key="item.id" :label="item.typeName" :value="item.id">
          </el-option>
        </el-select>

        <el-input clearable style="width: 150px" placeholder="操作编号" v-model="dg.ps.operMark">
        </el-input>

        <el-input clearable style="width: 150px" placeholder="摘要" v-model="dg.ps.remark">
        </el-input>

        <el-select clearable v-model="dg.ps.settleUname" placeholder="结算人账号选择" style="width: 130px">
          <el-option v-for="item in staffOptions" :key="item.baseUserId.uname" :label="item.baseUserId.realName"
            :value="item.baseUserId.uname">
          </el-option>
        </el-select>

        <el-select clearable v-model="dg.ps.status" placeholder="收支情况" style="width: 100px">
          <el-option label="收入" value="0"></el-option>
          <el-option label="支出" value="1"></el-option>
        </el-select>

        <!-- <el-input
          clearable
          style="width: 150px"
          placeholder="下订单账号"
          v-model="dg.ps.orderNum">
        </el-input>

        <el-select
          clearable
          v-model="dg.ps.operUname"
          placeholder="请选择操作员"
          style="width: 120px">
          <el-option
            v-for="item in staffOptions"
            :key="item.baseUserId.id"
            :label="item.baseUserId.realName"
            :value="item.baseUserId.id">
          </el-option>
        </el-select> -->

        <el-button type="primary" icon="el-icon-search" @click="getDgList">
          搜索
        </el-button>

        <el-button type="primary" icon="el-icon-plus" @click="setAddAccountMd({ state: true })">
          新增
        </el-button>

        <el-button type="primary" icon="el-icon-edit" @click="setUpdateAccountMd({ state: true })">
          修改
        </el-button>

        <el-button type="primary" icon="el-icon-delete" @click="delBankRecord">
          删除
        </el-button>

        <el-button type="primary" icon="el-icon-s-check" @click="setMonthSettleMd({ state: true })">
          月结算
        </el-button>

        <el-button type="primary" icon="el-icon-download" @click="handleExport">
          导出
        </el-button>
      </div>

      <TableSelfSet v-if="dg.columns.length > 0" :tbTitle="'银行记账'" :dgName="dg.dgName" :tbId="dg.tbName"
        :srcCols="dg.srcCols" :columns="dg.columns" :showSeledInfo="this" @saveSet="saveTbSet" />
    </div>

    <el-table :ref="dg.tbName" :data="dg.list" row-key="id" :height="bodyHeight" border fit :row-class-name="rowClassName"
      @header-dragend="dragHeader" @selection-change="selRowChange">
      <el-table-column fixed="left" type="index" label="编号" align="center" :resizable="false" width="40">
      </el-table-column>
      <el-table-column fixed="left" type="selection" align="center" :resizable="false" width="40">
      </el-table-column>
      <fragment v-for="col in dg.columns" :key="col.field">
        <el-table-column :class-name="dg.dgName" :prop="col.field" :label="col.label" :width="col.width">
          <template slot-scope="{row}">
            <template v-if="col.field == 'operUser'">{{ getOperUser(row) }}</template>
            <template v-else-if="col.field == 'isCheck'">{{ getCheck(row) }}</template>
            <template v-else-if="col.field == 'cusName'">{{ getCusName(row) }}</template>

            <template v-else-if="col.field == 'operNote'">
              <span
                v-html="row.operNote.replace(/\(/g, '<br />').replace(/\)/g, '；<br />').replace(/&nbsp;,/g, '<br />')"></span>
            </template>

            <template v-else-if="col.field == 'settleUser'">
              {{ row.settleUser && row.settleUser.realName + '-' + row.settleUser.phone }}
            </template>

            <template v-else-if="col.field == 'tradeInMoney'">
              <span :class="row.tradeInMoney > 0 ? 'c-green' : ''">{{ row.tradeInMoney }} 元</span>
            </template>

            <template v-else-if="col.field == 'tradeOutMoney'">
              <span :class="row.tradeOutMoney > 0 ? 'c-red' : ''">{{ row.tradeOutMoney }} 元</span>
            </template>

            <template v-else>{{ getColVal(row, col.field) }}</template>
          </template>
        </el-table-column>
      </fragment>
    </el-table>
    <Pagination v-show="dg.total > 0" :total="dg.total" :page.sync="dg.ps.page" :limit.sync="dg.ps.rows"
      @pagination="getDgList" />

    <input ref="inputRef" type="file" id="file" name="file" style="display: none" @change="handleChange" />

    <AddAccount v-if="addAccountMd.state" @myClick="setAddAccountMd" @reloadDg="getDgList" />

    <UpdateAccount v-if="updateAccountMd.state" :myData="updateAccountMd" @myClick="setUpdateAccountMd"
      @reloadDg="getDgList" />

    <MonthlyAccount v-if="monthSettleMd.state" @myClick="setMonthSettleMd" @reloadDg="getDgList" />
  </div>
</template>

<script>
import DataGridBase from "@/views/mixins/DataGridBase";
import DataGridResize from "@/views/mixins/DataGridResize";
import elDragDialog from "@/directive/el-drag-dialog";
import TableSelfSet from '@/components/TableSelfSet';
import Pagination from "@/components/Pagination";

import { exportExcel } from '@/utils/exportFile';
import { downFiles } from "@/api/export";
import AddAccount from "./add-account";
import UpdateAccount from "./update-account";
import MonthlyAccount from "./monthly-account";

import * as commonSer from "@/api/services/common.service";
import * as orderSer from "@/api/services/order.service";

export default {
  name: "BankAccount",
  mixins: [DataGridBase, DataGridResize],
  directives: { elDragDialog },
  components: { TableSelfSet, Pagination, AddAccount, UpdateAccount, MonthlyAccount },
  data() {
    let cols = [
      { label: '交易时间', field: 'tradeTime', width: 150 },
      { label: '客户名称', field: 'cusName', width: 140 },
      { label: '银行名称', field: 'myBankName', width: 140 },
      { label: '银行账号', field: 'myBankNum', width: 180 },
      { label: '报销状态', field: 'isCheck', width: 100 },
      { label: '金额类型', field: 'moneyTypeId.typeName', width: 120 },
      { label: '收入', field: 'tradeInMoney', width: 120 },
      { label: '对方户名', field: 'transName', width: 120 },
      { label: '对方账号', field: 'transNum', width: 150 },
      { label: '添加时间', field: 'addTime', width: 150 },
      { label: '支出', field: 'tradeOutMoney', width: 120 },
      { label: '余额', field: 'balance', width: 120 },
      { label: '摘要', field: 'remark', width: 120 },
      { label: '操作编号', field: 'opermark', width: 100 },
      { label: '操作备注', field: 'operNote', width: 320 },
      { label: '结算人', field: 'settleUser', width: 100 },
    ];

    return {
      totalPay: 0,
      totalGath: 0,
      bankBalance: 0,

      dg: {
        dgName: 'dg',
        tbName: "bankAccountTb",
        total: 0,
        list: [],
        srcCols: cols,
        columns: [],
        selRows: [],
        ps: {
          // 过滤参数
          page: 1, rows: 20,
          // 选择银行
          bankArr: [],
          // 对方户名
          transName: "",
          // 客户名称
          cusName: "",
          // 时间查询类型
          timeType: "0",
          // 起止日期
          setime: [],
          // 结束时间
          eTime: "",
          // 开始时间
          sTime: "",
          // 交易金额
          findMoney: "",
          // 报销状态
          isCheck: "",
          // 财务备注
          financeNote: "",
          // 金额类型id
          moneyType: "",
          // 操作编号
          operMark: "",
          // 摘要
          remark: "",
          // 结算人账号
          settleUname: "",
          // 收支情况
          status: "",
          // 下账订单号
          orderNum: "",
          // 下账人uname
          operUname: "",
        },

      },

      // 月结-弹框
      monthSettleMd: { state: false },
      // 添加银行账-弹框
      addAccountMd: { state: false },
      // 修改银行账-弹框
      updateAccountMd: { state: false },

      currentData: null,
      moneyOptions: [],
      bankOptions: [],
      staffOptions: [],
    };
  },
  created() {
    const that = this;

    that.initTbSetData(that.dg.dgName);

    that.getDgList();
    that.init();
  },
  computed: {
    getBalance() {
      let reg = /^[0-9]+.?[0-9]*$/;
      let result = reg.test(this.bankBalance) ? "元" : "";
      return this.bankBalance + result;
    },
  },
  methods: {
    init() {
      commonSer.getMoneyTypeDict().then((res) => {
        this.moneyOptions = res.mTypes;
      });
      commonSer.getBankListDict().then((res) => {
        this.bankOptions = res.banks;
      });
      commonSer.getStaffCombo({ isContainDriver: 1 }).then((res) => {
        this.staffOptions = res.data;
      });
    },
    getCheck(row) {
      let state = { "-1": "已结算", 0: "未操作", 1: "已报销" };
      return state[row.isCheck] || "--";
    },
    getOperUser(row) {
      if (!row.operUser) return "--";
      return row.operUser;
    },
    getCusName(row) {
      let name = row.cusName;
      if (!name) return "--";
      return name.split("-")[0] || "--";
    },

    // 导入银行账Excel
    handleImport() {
      const that = this, U = that.U, ps = that.dg.ps, fileInp = that.$refs.inputRef;

      if (!ps.bankArr || ps.bankArr.length == 0) {
        U.qerror("请先选择银行信息");
      } else if (ps.bankArr.length > 1) {
        U.qerror('只能选择一个银行');
      } else {
        fileInp.value = null;
        fileInp.click();

        that.fileTradeBank = ps.bankArr[0];
        this.params = {
          btlFile: "",
          tradeBank: ps.bankArr[0],
        };
      }
    },
    // 文件选择改变事件
    handleChange(e) {
      const that = this, U = that.U, fileInp = that.$refs.inputRef;

      let file = e.target.files[0];

      let form = new FormData();
      form.append("btlFile", file);
      form.append("tradeBank", that.fileTradeBank);

      U.qconfim('是否立即上传？', '导入提示').then(r => {
        if (r) {
          orderSer.importTemplate(form).then((res) => {
            fileInp.value = null;

            if (res.code !== 1) {
              U.qerror(res.msg);
            } else {
              U.qsuccess(res.msg);

              that.getDgList();
            }
          });
        }
      });
    },

    // 下载导出excel模板文件
    handleDown() {
      commonSer.getBtModelDown().then((res) => {
        console.log(res)
        downFiles(res, "银行记账");
      });
    },

    // 显示/隐藏-月结算-弹框
    setMonthSettleMd(e) {
      this.monthSettleMd = e;
    },
    // 显示/隐藏-添加银行账-弹框
    setAddAccountMd(e) {
      this.addAccountMd = e;
    },
    // 显示/隐藏-修改银行账-弹框
    setUpdateAccountMd(e) {
      const that = this, U = that.U, md = that.updateAccountMd, rows = that.getSeledRows();

      if (!e.state) {
        md.state = false;
        md.obj = null;
      } else {
        if (rows.length !== 1) {
          U.qerror(`${rows.length == 0 ? '请' : '只能'}选择一条数据`);
        } else {
          let row = rows[0];
          if (row.isCheck !== 0) {
            U.qerror("所选银行账【不是未操作】，不允许修改");
          } else {
            md.obj = row;
            md.state = true;
          }
        }
      }
    },
    // 删除-银行流水记录
    delBankRecord() {
      let that = this, U = that.U, rows = that.getSeledRows();

      if (!rows.length || rows.length == 0) {
        U.qerror("请勾选要删除的数据");
      } else {
        let isObj = rows.find(it => it.isCheck != 0);
        if (isObj) {
          U.qerror(`所选第${isObj.index + 1}行数据【不是未审核】，不能删除`);
        } else {
          let BankArr = [], IdsArr = [];
          rows.forEach(it => {
            IdsArr.push(it.id);
            BankArr.push(it.myBankNum);
          });

          let isCheckBank = [...new Set(BankArr)];
          if (isCheckBank.length !== 1) return U.qerror("不能删除不同银行账号信息");

          U.qconfim(`确定<span class="c-red">删除所选记录</span>？`).then(r => {
            if (r) {
              let ps = { ids: IdsArr.join(","), myBankNum: isCheckBank[0] };
              orderSer.deleteBankAccount(ps).then(res => {
                if (res.code != 1) {
                  U.qerror(res.msg);
                } else {
                  U.qsuccess(res.msg);

                  that.getDgList();
                }
              });
            }
          });
        }
      }
    },
    getAddMdState(e) {
      this.$refs[this.dg.tbName].clearSelection();
      this.dg.selRows = []
      this.md = {
        mon: { state: false },
      }
      this.currentData = ''
    },
    // 获取-表格列表数据
    getDgList() {
      let that = this, U = that.U, ps = U.scopy(that.dg.ps);

      ps.sTime = (ps.setime && ps.setime.length > 0) ? ps.setime[0] : '';
      ps.eTime = (ps.setime && ps.setime.length > 0) ? ps.setime[1] : '';
      delete ps.setime;

      if (ps.bankArr?.length > 0) {
        ps.bankName = ps.bankArr.map(it => it.split('/')[0]).join(',');
        ps.bankNo = ps.bankArr.map(it => it.split('/')[1]).join(',');
      }
      delete ps.bankArr;

      orderSer.getBankTradeList(ps).then((res) => {
        const { totalPay, totalGath, bankBalance, count } = res;
        if (res.code === 1) {
          that.totalPay = totalPay;
          that.totalGath = totalGath;
          that.bankBalance = bankBalance;

          let list = res.data;
          list.forEach(it => { it.dgName = that.dg.dgName; });
          that.dg.list = list
          that.dg.total = count;
        }
      });
    },
    // 导出excel数据
    handleExport() {
      let that = this, U = that.U, ps = U.scopy(that.dg.ps);

      ps.sTime = (ps.setime && ps.setime.length > 0) ? ps.setime[0] : '';
      ps.eTime = (ps.setime && ps.setime.length > 0) ? ps.setime[1] : '';
      delete ps.setime;

      ps.rows = that.dg.total;
      orderSer.expBtlBankEx(ps).then(res => {
        if (res.code !== 1) {
          this.U.qerror(res.msg);
        } else {
          exportExcel({
            filename: '银行流水',
            data: res.data,
            enumData: {
              "tradeTime": "交易时间",
              "cusName": "客户名称",
              "myBankName": "银行名称",
              "myBankNum": "银行账号",
              "isCheck": "报销状态",
              "moneyTypeId": "金额类型",
              "tradeInMoney": "收入",
              "transName": "对方户名",
              "transNum": "对方账号",
              "addTime": "添加时间",
              "tradeOutMoney": "支出",
              "balance": "余额",
              "remark": "摘要",
              "operMark": "操作编号",
              "operNote": "操作备注",
              "settleUser": "结算人",
            }
          });
        }
      })
    }
  },
};
</script>
